package com.yuantu.judiciary.utils;

import com.alibaba.fastjson2.JSON;
import com.antherd.smcrypto.sm2.Keypair;
import com.antherd.smcrypto.sm2.Sm2;
import com.yuantu.judiciary.common.SysCode;
import com.yuantu.judiciary.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * Sm2 加解密工具类
 *
 * @author syw
 * @since 2023-06-08
 */
@Slf4j
public class Sm2Util {

    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "2c29b500bd3b521de75a1cea51f462b4e8ce10bdeb212118d21e641bebbaeed4";
    /**
     * 公钥
     */
    private static final String PUBLIC_KEY = "04043dca81698d169f07acc6211bbba44a4eb8105a9dcd5272d403c8fd0b7f93c207849e00ecb3d469669c508f46d74d5079aad6f9a864581b7353589018d56971";

    /**
     * 获取公钥和私钥
     *
     * @return .
     */
    public static Keypair getKeypair() {
        return Sm2.generateKeyPairHex();
    }

    /**
     * 加密结果
     *
     * @param msg .
     * @return .
     */
    public static String encrypt(String msg) {
        return Sm2.doEncrypt(msg, PUBLIC_KEY);
    }
    public static String encrypt(String msg, String publicKey) {
        return Sm2.doEncrypt(msg, publicKey);
    }

    /**
     * 解密结果
     *
     * @param encryptData .
     * @return .
     */
    public static String decrypt(String encryptData) {
        return Sm2.doDecrypt(encryptData, PRIVATE_KEY);
    }
    public static String decrypt(String encryptData, String privateKey) {
        return Sm2.doDecrypt(encryptData, privateKey);
    }

    /**
     * 解密并转换入参
     */
    public static <T> T transferDecryptParam(String param, Class<T> clazz, String privateKey) throws ServiceException {
        try {
            String decryptParam = Sm2Util.decrypt(param, privateKey);
            AssertUtil.assertTrue(StringUtils.isNotBlank(decryptParam), SysCode.OPEN_API_DECODE_ERROR);
            return JSON.parseObject(JSON.parseObject(decryptParam).toJSONString(), clazz);
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("开放接口参数解密异常: " + e.getMessage(), e);
            throw new ServiceException(SysCode.SYSTEM_ERROR);
        }
    }

    public static void main(String[] args) {
//        System.out.println(Sm2Util.getKeypair());
        System.out.println(Sm2Util.decrypt("29cc4d56fe477591cbb4026a5e1e9f88274d989a108e12844bbe2b732bc605507768d1cb096dac4fcccac691b1f2278f14bc9f2b1711d813e32f8ab8593fd5bb10396a6554feb768e1ebdd6890a0fb42a5aeedcc6c5ae6180ee21bf1462899703727"));


    }

}
